<script setup>
import * as Cesium from "cesium";
import { onMounted, ref } from "vue";
import RenderUtil from "../../utils/RenderUtil";
import CustomPrimitive from "../../utils/CustomPrimitive";
import MyPrimitive from "../../primitives/MyPrimitive";

let viewer, baseLayer, enumLayer;
const tianditutkArr = [
  "590447cdbdf97775b57588a69ebb903d",
  "75f1cc913e8d68f7bd4b6f6383f78ceb",
  "4c4c0f03b0bdb58811f657fec0c09eb5",
];
// ['590447cdbdf97775b57588a69ebb903d', '75f1cc913e8d68f7bd4b6f6383f78ceb', '4c4c0f03b0bdb58811f657fec0c09eb5']
const tianditutk =
  tianditutkArr[Math.floor(Math.random() * tianditutkArr.length)];
Cesium.Ion.defaultAccessToken =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJhZjE5ZTBhZC00YzE1LTQyMWYtOWM4MC00NmFlZjZhOGI3ZDciLCJpZCI6MTI4NTI2LCJpYXQiOjE2OTg4MzczOTN9.26EHXec7Ufty_B4e5_YWcB0t--zlquly7r66WVSS9wE";
// 设置Cesium默认视角
Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(
  108.4,
  21.3,
  129.3,
  48.6
);
// 创建材质
function createTexture(context) {
  const colorTextureOptions = {
    context: context,
    width: context.drawingBufferWidth,
    height: context.drawingBufferHeight,
    pixelFormat: Cesium.PixelFormat.RGBA,
    pixelDatatype: Cesium.PixelDatatype.UNSIGNED_BYTE
  };
  const depthTextureOptions = {
    context: context,
    width: context.drawingBufferWidth,
    height: context.drawingBufferHeight,
    pixelFormat: Cesium.PixelFormat.DEPTH_COMPONENT,
    pixelDatatype: Cesium.PixelDatatype.UNSIGNED_INT
  };
  const textures = {
    color: RenderUtil.createTexture(colorTextureOptions),
    depth: RenderUtil.createTexture(depthTextureOptions)
  }
  return textures;
}
// 创建渲染帧缓冲区
function createRenderingFramebuffers(context, textures) {
  const framebuffers = {
    commonFramebuffer: RenderUtil.createFramebuffer(context, textures.color, textures.depth),
  }
  return framebuffers;
}
// 创建自定义Geometry
function createCustomGeometry() {
  const myPrimitive = new MyPrimitive();
  return myPrimitive.generateGeometry()
}
// 创建自定义Primitive
function createCustomPrimitive() {
  const framebuffers = createRenderingFramebuffers(viewer.scene.context, createTexture(viewer.scene.context));
  const testVertex = `
  in vec3 position3DHigh;
  in vec3 position3DLow;
  in float batchId;
  in vec4 color;
  in vec3 position;
  out vec4 v_color;

  void main() {
    // vec4 pos = czm_computePosition();   // 返回当前这个顶点的位置
    v_color = color;
    gl_Position = czm_projection * czm_modelView * vec4(position, 1.0);
  }
`

  const testFrag = `
  in vec4 v_color;
  uniform float randomNumber;
  out vec4 myFragColor;

  void main() {
    float time = fract(czm_frameNumber / 60.0);
    myFragColor = vec4(1.0, 1.0, 0.0, 1.0);
    // myFragColor = vec4(randomNumber, randomNumber * czm_frameNumber, randomNumber, 1.0);
  }
`
  const customPrimitive = new CustomPrimitive({
    commandType: 'Draw',
    attributeLocations: {
      position: 0,
      color: 1
    },
    geometry: createCustomGeometry(),
    primitiveType: Cesium.PrimitiveType.LINES,
    uniformMap: {
      randomNumber() {
        return Math.random()
      }
    },
    vertexShaderSource: new Cesium.ShaderSource({
      sources: [testVertex]
    }),
    fragmentShaderSource: new Cesium.ShaderSource({
      sources: [testFrag]
    }),
    rawRenderState: RenderUtil.createRawRenderState({
      viewport: undefined,
      depthTest: {
        enabled: true
      },
      depthMask: true
    }),
    // 输出的纹理，如果不设置，则默认输出颜色缓冲区
    // framebuffer: framebuffers.commonFramebuffer,
    framebuffer: undefined
    // 是否自动清除颜色缓冲区，默认为false，如果设置为true，则在渲染新帧之前会自动清除颜色缓冲区，从而导致地球不见。
    // autoClear: true  
  });
  viewer.scene.primitives.add(customPrimitive);
  return customPrimitive;
}
onMounted(() => {
  baseLayer = new Cesium.ImageryLayer(
    new Cesium.WebMapTileServiceImageryProvider({
      url:
        "http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=" +
        tianditutk,
      layer: "tdtImgLayer",
      style: "default",
      format: "image/jpeg",
      tileMatrixSetID: "GoogleMapsCompatible", //使用谷歌的瓦片切片方式
      show: true,
    })
  );
  viewer = new Cesium.Viewer("cesiumContainer", {
    // animation: false, // 动画小组件
    baseLayerPicker: false, // 底图组件，选择三维数字地球的底图
    fullscreenButton: false, // 全屏组件
    vrButton: false, // VR模式
    geocoder: false, // 地理编码搜索组件
    homeButton: false, // 首页，点击之后将视图跳转到默认视角
    infoBox: false, // 信息框
    sceneModePicker: false, // 场景模式，切换2D、3D和Columbus Views（CV）模式
    selectionIndicator: false, // 是否显示选取指示器组件
    // timeline: false, // 时间轴
    navigationHelpButton: false, // 帮助提示，如何操作数字地球
    navigationInstructionsInitiallyVisible: false,
    // terrain: new Cesium.Terrain.fromWorldTerrain({
    //   url: Cesium.IonResource.fromAssetId(3956),
    //   requestWaterMask: true,    // 请求水体效果所需要的海水波浪数据
    //   requestVertexNormals: true   // 请求地形照明数据
    // }),
    baseLayer,
    contextOptions: {
      requestWebgl2: true, // 开启webgl2渲染
    },
  });

  enumLayer = new Cesium.ImageryLayer(
    new Cesium.WebMapTileServiceImageryProvider({
      url:
        "http://t0.tianditu.com/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=" +
        tianditutk,
      layer: "tdtCiaLayer",
      style: "default",
      format: "image/jpeg",
      tileMatrixSetID: "GoogleMapsCompatible", //使用谷歌的瓦片切片方式
      show: true,
    })
  );
  viewer.imageryLayers.add(enumLayer);
  viewer.imageryLayers.add(enumLayer);
  window.baseLayer = baseLayer;
  window.viewer = viewer;
  window.enumLayer = enumLayer;
  createCustomPrimitive();
});
</script>

<template>
  <div id="cesiumContainer"></div>
</template>

<style lang="scss">
#cesiumContainer {
  width: 100vw;
  height: 100vh;
  position: relative;

  .cesium-viewer-bottom {
    visibility: hidden;
  }
}
</style>
